package com.dz.controller.visitor;

import cn.hutool.db.PageResult;
import com.dz.annotation.OperationLog;
import com.dz.bean.Guide;
import com.dz.bean.Transaction;
import com.dz.bean.Visitor;
import com.dz.service.BookingService;
import com.dz.service.GuideService;
import com.dz.service.TransactionService;
import com.dz.service.VisitorService;
import com.dz.util.EmailUtil;
import com.dz.util.Page;
import com.dz.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/visitor/transaction")
@CrossOrigin
public class TransactionController {

    @Autowired
    private TransactionService transactionService;

    @Autowired
    private GuideService guideService;

    @Autowired
    private VisitorService visitorService;

    @Autowired
    private BookingService bookingService;

    /**
     * 创建交易记录
     */
    @PostMapping
    @OperationLog("提交交易")
    public Result createTransaction(@RequestBody Transaction transaction) {
        try {
            // 保存交易记录
            transactionService.add(transaction);

            if (transaction.getBookingId() != null)
                try {
                    bookingService.updateToPaid(Integer.valueOf(transaction.getBookingId()));
                } catch (Exception e) {
                    System.out.println("更新支付状态失败" + e.getMessage());
                }

            // 获取地陪和游客信息
            Guide guide = guideService.findById(transaction.getGuideId());
            //Visitor visitor = visitorService.findById(transaction.getVisitorId());

            // 发送邮件给地陪
            if (guide != null && guide.getEmail() != null) {
                String guideMessage = "您有新的工作安排，详情请上\"颜途\"旅游服务平台查看";
                EmailUtil.sendWorkEmail(guide.getEmail(), guideMessage);
            }

            return Result.success("支付成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "支付失败: " + e.getMessage());
        }
    }

    /**
     * 获取交易记录分页数据
     */
    @GetMapping("/page")
    public Result getTransactionPage(Page page, Transaction transaction) {
        transactionService.page(page, transaction);
        return Result.success(page);
    }
}

